﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Objects;
using System.Linq.Expressions;
using CoolCode.Linq.Expressions;

namespace CoolCode.Data.Entity
{
    [ProviderName("System.Data.EntityClient")]
    public class XDataContext : IDataContext
    {
        #region IDataContext Members

        public string ConnectionString { get; set; }

        internal ObjectContext InnerContext;

        public XDataContext(ObjectContext innerContext)
        {
            InnerContext = innerContext;
            ConnectionString = innerContext.Connection.ConnectionString;
            LoadOptions = new LoadOption(innerContext);
        }

        public IRepository<T> CreateRepository<T>() where T : class
        {
            return new Repository<T>(this);
        }

        public void SubmitChanges()
        {
            InnerContext.SaveChanges();
        }

        public ILoadOption LoadOptions { get; private set; }

        #endregion

        #region IDisposable Members

        public virtual void Dispose()
        {
            if (InnerContext != null)
            {
                InnerContext.Dispose();
            }
        }

        #endregion

        public class LoadOption : ILoadOption
        {
            private ObjectContext db;

            public List<Tuple<Type, string>> Loaders { get; private set; }

            public LoadOption(ObjectContext context)
            {
                db = context;
                this.Loaders = new List<Tuple<Type, string>>();
            }

            #region ILoadOption Members

            public ILoadOption LoadWith<T>(Expression<Func<T, object>> property)
            {
                //TODO:
                this.Loaders.Add(
                    new Tuple<Type, string>( property.Parameters[0].Type, property.Body .GetMemberName())
                     );  
                return this;
            }

            public void EndLoad()
            {
                //TODO:
            }

            #endregion
        }
    }
}
